from rest_framework import serializers
from rest_framework.serializers import Serializer, ModelSerializer

from system.models import Permissions

class PermissionModelSerializer(ModelSerializer):
    """权限序列化器"""
    class Meta:
        model = Permissions
        fields = "__all__"


class PermissionsSerializer(Serializer):
    """序列化器"""
    id = serializers.CharField()
    name = serializers.CharField(max_length=30)
    sign = serializers.CharField(max_length=30)
    menu = serializers.BooleanField()
    method = serializers.CharField(max_length=8, source='get_method_display')
    path = serializers.CharField(max_length=200)
    desc = serializers.CharField(max_length=30)
    pid = serializers.CharField(source='pid_id')

    @property
    def data(self):
        return_data = super().data
        tree_data = []
        tree_dict = {}
        for item in return_data:
            tree_dict[item.get('id')] = item

        for key, value in tree_dict.items():
            pid = value.get('pid', None)
            if pid is not None:
                parent = tree_dict.get(pid)
                parent.setdefault('children', []).append(value)
            else:
                tree_data.append(value)

        return tree_data